package com.wang.tingge.servlet.track;

import com.wang.tingge.repository.TrackRepo;
import com.wang.tingge.util.Log;
import com.wang.tingge.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/studio/track/upload.do")
//要接收enctype==multipart/formdata form表单数据 必须用@MultipartConfig修饰
@MultipartConfig  //不用@MultipartConfig修饰 就会出现500错误，错误原因就会提示没有修饰
public class uploadDoServlet extends HttpServlet {
    private final TrackRepo trackRepo=new TrackRepo();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果用户没有登录先提示用户登录
        UserVO userVO = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            userVO=(UserVO)session.getAttribute("currentUser"); //session中的用户时登录时放进去
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer=resp.getWriter();
        if(userVO==null){
            //用户没有登录
            Log.println("用户未登录");
            writer.println("请登录用户");
            return;
        }

        //用户已登录
        Log.println("登录用户为：");

        //从请求中获取我们需要的信息
        req.setCharacterEncoding("utf-8");
        String title=req.getParameter("title");
        Log.println("获取到的title是："+title);

        Part track=req.getPart("track");
        String type=track.getContentType();
        Log.println("获取到的type是："+type);
        InputStream contentInputStream=track.getInputStream(); //可以从这个InputStream中读取到音频内容

        //将拿到的数据插入数据库表里，由于做的操作比较简单，就不引入service，直接使用trackRepo对象
        trackRepo.insert(userVO.uid,title,type,contentInputStream);
        Log.println("上传成功");

        //响应插入成功
        writer.println("上传成功");
    }
}
